package com.s63.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.s63.entity.AjaxResult;
import com.s63.entity.User;
import com.s63.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2023-11-06
 */
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
public class UserController {
    private final IUserService userService;

    @GetMapping
    @PreAuthorize("hasAuthority('user:list')")
    public AjaxResult list(User user, int pageNo, int pageSize) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class).like(StringUtils.hasText(user.getNickName()), User::getNickName, user.getNickName())
                .eq(user.getDeptId() != null, User::getDeptId, user.getDeptId());
        Page<User> page = userService.page(Page.of(pageNo, pageSize), queryWrapper);
        return AjaxResult.ok(page);
    }

    @GetMapping("/{userId}")
    @PreAuthorize("hasAuthority('user:list')")
    public AjaxResult get(@PathVariable Long userId) {
        User user = userService.getById(userId);
        user.setPassword("");
        return AjaxResult.ok(user);
    }

    @PostMapping
    @PreAuthorize("hasAuthority('user:add')")
    public AjaxResult add(@RequestBody User user) {
        userService.asyncSave(user);
        return AjaxResult.ok();
    }

    @DeleteMapping("/{userId}")
    @PreAuthorize("hasRole('manager')")
    public AjaxResult del(@PathVariable Long userId) {
        return AjaxResult.ok(userService.removeById(userId));
    }

    @PutMapping
    @PreAuthorize("hasAuthority('user:update')")
    public AjaxResult update(@RequestBody User user) {
        return AjaxResult.ok(userService.updateById(user));
    }

}
